package com.bawei.lifecycle_test;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;


import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

//观察者实现LifecycleObserver感知Service
public class MyLocationObserver implements LifecycleObserver {
    private static final String TAG = "MyLocationObserver";
    private LocationManager locationManager;//定位管理者
    private MyLocationListener locationListener;//定位监听
    private Context context;


    public MyLocationObserver(Context context) {
        this.context = context;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void create(){
        Log.d(TAG, "服务被创建，注册监听，开始获得定位信息: ");
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        //注册监听
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, locationListener);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void destory(){
        Log.d(TAG, "服务被销毁，移除监听，避免内存泄漏: ");
        locationManager.removeUpdates(locationListener);
    }

    static class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG,"location changed:"+location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {//定位可用
            Log.d(TAG,"可用");

        }

        @Override
        public void onProviderDisabled(String provider) {//定位不可用
            Log.d(TAG,"不可用");
        }
    }

}
